package kz.pompei.ifacer.main;

import java.awt.event.KeyEvent;
import java.lang.reflect.Field;

public class KeyAcceptor {
  private boolean ctrl = false, shift = false, alt = false;
  int vk;
  
  private KeyAcceptor() {}
  
  public static KeyAcceptor parse(String key) {
    KeyAcceptor ret = new KeyAcceptor();
    
    key = key.toUpperCase();
    if (key.contains("CTRL+")) {
      ret.ctrl = true;
      key = key.replaceAll("CTRL\\+", "");
    }
    if (key.contains("SHIFT+")) {
      ret.shift = true;
      key = key.replaceAll("SHIFT\\+", "");
    }
    if (key.contains("ALT+")) {
      ret.alt = true;
      key = key.replaceAll("ALT\\+", "");
    }
    
    try {
      Field field = KeyEvent.class.getField("VK_" + key);
      ret.vk = (Integer)field.get(null);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    
    return ret;
  }
  
  public boolean accept(KeyEvent e) {
    if (e.getKeyCode() != vk) return false;
    if (e.isControlDown() != ctrl) return false;
    if (e.isShiftDown() != shift) return false;
    if (e.isAltDown() != alt) return false;
    return true;
  }
  
  @Override
  public String toString() {
    return "KeyAcceptor [ctrl=" + ctrl + ", shift=" + shift + ", alt=" + alt + ", vk=" + vk + "]";
  }
}